package controllers

import (
	"encoding/json"

	. "fanhantech.com/tagdata/message"
	"fanhantech.com/tagdata/models"
	"github.com/astaxie/beego"
)

type UserRightController struct {
	beego.Controller
}

type ResponseUserRight struct {
	Username string `json:"username"`
	Project  string `json:"project"`
	Role     string `json:"role"`
}

// Get /api/user/:username/rights [GET]
func (c *UserRightController) QueryUserRight() {
	username := c.Ctx.Input.Param(":username")
	rights, err := models.QueryUserRightByUsername(username)
	if err != nil {
		c.Data["json"] = NewResponseFor("user.query.fail")
		c.ServeJSON()
		return
	}
	responseRights := make([]ResponseUserRight, 0)
	for _, right := range rights {
		responseRight := ResponseUserRight{}
		responseRight.Username = right.Username
		responseRight.Project = right.Name
		switch right.Role {
		case 1:
			responseRight.Role = "管理员"
		case 2:
			responseRight.Role = "审核用户"
		default:
			responseRight.Role = "普通用户"
		}
		responseRights = append(responseRights, responseRight)
	}
	rsp := NewResponse()
	rsp.Data = responseRights
	c.Data["json"] = rsp
	c.ServeJSON()
}

type FormUserRight struct {
	Username string `valid:"Required;AlphaDash"`
	Project  string `valid:"Required"`
	Role     string `valid:"Required"`
}

// Post /api/user/rights [POST]
func (c *UserRightController) CreateUserRight() {
	right := FormUserRight{}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &right)
	if err != nil {
		c.Data["json"] = NewResponseFor("user.data.verification.error")
		c.ServeJSON()
		return
	}
	role := 0
	switch right.Role {
	case "管理员":
		role = 1
	case "审核用户":
		role = 2
	case "普通用户":
		role = 3
	default:
		c.Data["json"] = NewResponseFor("user.data.verification.error")
		c.ServeJSON()
		return
	}
	err = models.CreateUserRight(right.Username, right.Project, role)
	if err != nil {
		c.Data["json"] = NewResponseFor("user.right.create.fail")
		c.ServeJSON()
		return
	}
	c.Data["json"] = NewResponseFor("user.right.create.success")
	c.ServeJSON()
}

// Post /api/user/:username/rights [POST]
func (c *UserRightController) UpdateUserRight() {
	right := FormUserRight{}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &right)
	if err != nil {
		c.Data["json"] = NewResponseFor("user.data.verification.error")
		c.ServeJSON()
		return
	}
	role := 0
	switch right.Role {
	case "管理员":
		role = 1
	case "审核用户":
		role = 2
	case "普通用户":
		role = 3
	default:
		c.Data["json"] = NewResponseFor("user.data.verification.error")
		c.ServeJSON()
		return
	}
	err = models.UpdateUserRight(right.Username, right.Project, role)
	if err != nil {
		c.Data["json"] = NewResponseFor("user.right.update.fail")
		c.ServeJSON()
		return
	}
	c.Data["json"] = NewResponseFor("user.right.update.success")
	c.ServeJSON()
}
